package com.yl.chainStore.control.pay

import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.entity.pay.PayCustomerOrderDetail
import com.yl.chainStore.entity.sick.CustomerSubscribeLog
import com.yl.chainStore.pojo.vo.pay.*
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailSelectVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailToStatusVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailUpdateVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsSelectVo
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.IWebCompanyDeptService
import com.yl.chainStore.services.pay.*
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.chainStore.services.sick.ISickMedicalRecordsService
import com.yl.chainStore.util.payItemTypeListToTree
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.*

/**
 * 订单相关视图
 */
@RestController
@RequestMapping("pay/order")
open class PayCustomerOrderController(
    private val iCustomerInfoService: ICustomerInfoService,
    private val iWebCompanyDeptService: IWebCompanyDeptService,
    private val iPayCustomerOrderService: IPayCustomerOrderService,
    private val iItemRuleService: IItemRuleService,
    private val iOrderRuleService: IOrderRuleService,
    private val iCompanyUserService: ICompanyUserService,
    private val iCompanyDeptService: ICompanyDeptService,

    private val iSickMedicalRecordsService: ISickMedicalRecordsService,
    private val iCustomerSubscribeLogService: ICustomerSubscribeLogService
) : BaseCtrl() {

    /**
     * 挂号
     */
    @PostMapping("registered")
    @PermsCode("work:customer:registered")
    @Transactional(rollbackFor = [Exception::class])
    open fun registered(@RequestBody vo: CustomerRegisteredVo): ResponseBody {
        if (vo.customerId == 0L) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "请选择患者")
        }
        val customerRecordsDetailList =
            iCustomerInfoService.getCustomerRecordsDetailList(
                SickMedicalRecordsDetailSelectVo(
                    customerId = vo.customerId,
                    day = Date(),
                    deptId = getContext().subCompanyId
                )
            )

        if (customerRecordsDetailList.isNotEmpty()) {
            //如果有同一天的，直接替换
            val oldDetail = customerRecordsDetailList[0]
            val updateVo = SickMedicalRecordsDetailUpdateVo(
                id = oldDetail.id,
                medicalSourcesType = vo.medicalSourcesType,
                registeredType = vo.registeredType,
                medicalSources = vo.medicalSources,
                remark = vo.remark,
                masterUserId = vo.masterUserId,
                secondaryUserId = vo.secondaryUserId,
            )

            val updateDetailByDetailId = iSickMedicalRecordsService.updateDetailByDetailId(updateVo)
            if (updateDetailByDetailId.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return updateDetailByDetailId
            }
            val detail = iSickMedicalRecordsService.getDetailByDetailId(updateVo.id)

            if (detail != null) {
                iCustomerSubscribeLogService.updateByRecordDetail(detail)
            }
            if(oldDetail.status.code < Status.WAIT_AUDIT.code){
                val detailToStatus = iSickMedicalRecordsService.detailToStatus(SickMedicalRecordsDetailToStatusVo(id = oldDetail.id,Status.WAIT_AUDIT))
                if (detailToStatus.bodyIsError()) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                }
            }

            return returnSuccess()
        }

        val registered = iCustomerInfoService.registered(vo)
        if (registered.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return registered
        }
        return returnSuccess()
    }

    /**
     * 挂号所需就诊记录
     */
    @GetMapping("getCompanyUserRecord/{customerId}")
    @Transactional
    open fun getCompanyUserRecord(@PathVariable customerId: Long): ResponseBody {
        val recordList = iCustomerInfoService.getRecordList(
            SickMedicalRecordsSelectVo(
                customerId = customerId,
//					status = Status.PUSH
            )
        )
        val list = mutableListOf<Map<String, Any>>()
        for (record in recordList) {
            val map = mutableMapOf<String, Any>()
            map["id"] = record.id
            map["name"] = record.actionChief ?: "暂无内容"
            list.add(map)
        }
        return returnSuccess(
            list
        )
    }

    /**
     * 获取挂号来源类型
     */
    @GetMapping("getRegisteredSourceType")
    open fun getRegisteredSourceType(): ResponseBody {
        val typeList = mutableListOf<Map<String, Any>>()
        typeList.add(TypeEnum.CUSTOMER_SUBSCRIBE_SOURCE_EXTERNAL.getMap())
        typeList.add(TypeEnum.CUSTOMER_SUBSCRIBE_SOURCE_INTERNAL.getMap())
        return returnSuccess(typeList)
    }

    /**
     * 获取挂号类型
     */
    @GetMapping("getRegisteredType")
    open fun getRegisteredType(): ResponseBody {
        val typeList = mutableListOf<Map<String, Any>>()
        for (i in 461..480) {
            val type = TypeEnum.getEnum(i)
            if (type == TypeEnum.OTHER) {
                break
            }
            typeList.add(type.getMap())
        }
        return returnSuccess(typeList)
    }


    /**
     * 部门收款项目类型
     */
    @GetMapping("getDeptPayItemTypeList/{superId}")
    @Transactional
    open fun getDeptPayItemTypeTree(@PathVariable superId: Long): ResponseBody {
        val itemTypeList = iWebCompanyDeptService.getItemTypeList(
            SysCompanyPayItemTypeSelectVo(
                deptId = getContext().subCompanyId,
                superId = superId
            )
        )
        return returnSuccess(itemTypeList)
    }

    /**
     * 部门收款项目
     */
    @PostMapping("getDeptItemPage")
    @Transactional
    open fun getDeptItemPage(@RequestBody vo: SystemCompanyPayItemSelectVo): ResponseBody {
        vo.haveZeroCount = true
        return returnSuccess(iWebCompanyDeptService.getPayItemList(vo, getContext().subCompanyId))
    }

    @GetMapping("getTypeAndItemTree")
    @Transactional
    open fun getTypeAndItemTree(): ResponseBody {
        val itemTypeList = iWebCompanyDeptService.getItemTypeList(
            SysCompanyPayItemTypeSelectVo(
                deptId = getContext().subCompanyId,
            )
        )
        for (type in itemTypeList) {
            type.items = iWebCompanyDeptService.getPayItemList(
                SystemCompanyPayItemSelectVo(
                    onlyTypeId = type.id,
                    haveZeroCount = true

                ), getContext().subCompanyId
            )
        }
        return returnSuccess(payItemTypeListToTree(itemTypeList, 0L))
    }

    /**
     * 订单详情列表
     */
    @GetMapping("getOrderDetail/{id}")
    @Transactional
    open fun getOrderDetail(@PathVariable id: Long): ResponseBody {
        val detailList = iPayCustomerOrderService.getDetailList(id)
        return returnSuccess(detailList)
    }


    /**
     * 用户消费账户相关
     */
    @GetMapping("getCustomerAccount/{customerId}")
    @Transactional
    open fun getCustomerAccount(@PathVariable customerId: Long): ResponseBody {
        val account = iCustomerInfoService.getCustomerAccount(customerId, getContext().subCompanyId)
        val vo = CustomerAccountResultVo(
            balance = BigDecimal(account.balance.div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)).setScale(
                2,
                RoundingMode.HALF_UP
            ),
            integral = account.integral,
            amountOwed = BigDecimal(account.amountOwed.div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)).setScale(
                2,
                RoundingMode.HALF_UP
            ),
            orderSumMoney = BigDecimal(
                iCustomerInfoService.getCustomerOrderSumMoney(customerId, null)
                    .div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)
            ).setScale(2, RoundingMode.HALF_UP),
            paySumMoney = BigDecimal(
                iCustomerInfoService.getCustomerOrderAmountSumMoney(customerId, null)
                    .div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)
            ).setScale(2, RoundingMode.HALF_UP),

//			paySumMoney = BigDecimal(
//				iCustomerInfoService.getCustomerPaySumMoney(customerId,null).div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)
//			).setScale(2, RoundingMode.HALF_UP),
        )
        val list = iCustomerInfoService.getCustomerCouponsList(
            PayCustomerCouponsSelectVo(
                customerId = customerId,
                companyId = getContext().companyId,
                subCompanyId = getContext().subCompanyId,
                unFlag = Status.COMPLETE,
                nowTime = Date()
            )
        )
        for (i in list) {
            when (i.type) {
                TypeEnum.CUSTOMER_COUPONS_CASH -> {
                    vo.couponsCashCount++
                }
                TypeEnum.CUSTOMER_COUPONS_PACKAGE -> {
                    vo.couponsPackageCount++
                }
                TypeEnum.CUSTOMER_COUPONS_DISCOUNT -> {
                    vo.couponsDiscountCount++
                }
                else -> {
                }
            }
        }
        return returnSuccess(vo)
    }

    /**
     * 客户订单（全部患者处 付过款的）
     */
    @PostMapping("getCustomerOrder")
    @PermsCode("customer:order:list")
    @Transactional
    open fun getCustomerOrder(@RequestBody vo: PayCustomerOrderSelectVo): ResponseBody {
        vo.onlyPaying = true
        val orderList = iCustomerInfoService.getOrderList(vo)
        for (order in orderList) {
            iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, order)
            iPayCustomerOrderService.getOrderLeftJoinSet(order)
            iPayCustomerOrderService.setOrderDetailItemInfo(order)
            iPayCustomerOrderService.setOrderDetailUserName(order)
            val dept = iCompanyDeptService.getDept(order.deptId)
            if (dept != null) {
                order.subCompanyName = dept.name
            }
        }
        return returnSuccess(orderList)
    }

    /**
     * 客户订单列表（划价处）
     */
    @PostMapping("getCustomerOrderList")
    @PermsCode("order:info:customer:list")
    @Transactional
    open fun getCustomerOrderList(@RequestBody vo: PayCustomerOrderSelectVo): ResponseBody {
        vo.statuses = listOf(Status.NEW_ADD, Status.WAIT_PAY)
        vo.subCompanyId = getContext().subCompanyId
        val orderList = iCustomerInfoService.getOrderList(vo)
        val resList = arrayListOf<PayCustomerOrder>()
        for (order in orderList) {
            order.details = iPayCustomerOrderService.getDetailList(order.id)
            iPayCustomerOrderService.accountingPayCustomerOrder(order)
            //因为项目是医院设置的，要么减，要么不减，所以不会报错
            val itemCompleteOrder = iItemRuleService.completeOrder(order)
            val orderCompleteOrder = iOrderRuleService.completeOrder(itemCompleteOrder.order)
            iPayCustomerOrderService.setOrderDetailItemInfo(orderCompleteOrder.order)
            iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, orderCompleteOrder.order)
            iPayCustomerOrderService.getOrderLeftJoinSet(orderCompleteOrder.order)
            iPayCustomerOrderService.setOrderDetailItemInfo(orderCompleteOrder.order)
            iPayCustomerOrderService.setOrderDetailUserName(orderCompleteOrder.order)
            resList.add(orderCompleteOrder.order)
        }
        //待加权限
        return returnSuccess(resList)
    }


    /**
     * 获取用户支付记录   余额变动记录 （全部患者处）
     */
    @PostMapping("getCustomerPayLog")
    @PermsCode("customer:pay:log:list")
    @Transactional
    open fun getCustomerPayLog(@RequestBody vo: PayCustomerMoneyFlowSelectVo): ResponseBody {
        // TODO: 2021/11/9 目前只显示支付
//		vo.subCompanyId = getContext().subCompanyId
        vo.useTypes = listOf(TypeEnum.PAY_TYPE_ORDER_REFUND, TypeEnum.PAY_TYPE_PAY_ORDER)
        return returnSuccess(iCustomerInfoService.getCustomerMoneyFlowList(vo))
    }

    /**
     * 用户支付类型
     */
    @GetMapping("getCustomerType")
    @Transactional
    open fun getCustomerType(): ResponseBody {
        val typeList = mutableListOf<Map<String, Any>>()
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_ACCOUNT.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_MONEY.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_ALIPAY.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_WECHAT.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_WORD_OF_MOUTH.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_BANK_CARD.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_ADVANCE_PAYMENT.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_SOCIAL_SECURITY_CARD.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_CITY_HEALTH_CARD.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_PROVINCIAL_HEALTH_CARD.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_PROVINCIAL_TRANSFER.getMap())
        typeList.add(TypeEnum.OTHER.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_TIDE_SHARE.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_PING_AN_GOOD_DOCTOR.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_MEITUAN.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_LETOOTH_MESH.getMap())
        typeList.add(TypeEnum.CUSTOMER_PAY_TYPE_NANCHANG_LINE.getMap())
        return returnSuccess(typeList)
    }

    /**
     * 获取当前用户欠款的订单
     */
    @GetMapping("getCustomerDebtOrder/{customerId}")
    @Transactional
    open fun getCustomerDebtOrder(@PathVariable customerId: Long): ResponseBody {
        val vo = PayCustomerOrderSelectVo(
            customerId = customerId,
            haveDebt = true,
            subCompanyId = getContext().subCompanyId
        )
        val orderList = iCustomerInfoService.getOrderList(vo)
        for (order in orderList) {
            iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, order)
            iPayCustomerOrderService.getOrderLeftJoinSet(order)
        }
        return returnSuccess(orderList)
    }

    /**
     * 订单核算
     *
     */
    @PostMapping("accountingOrder")
    @Transactional
    open fun accountingOrder(@RequestBody vo: PayCustomerOrderSaveVo): ResponseBody {
        //保存的变成订单实体类
        val order = iPayCustomerOrderService.saveOrderVoToOrder(vo)
        if (order.details.isNullOrEmpty()) {
            return returnSuccess(order)
        }

        //订单详情的数据变成
        val accountingPayCustomerOrder = iPayCustomerOrderService.accountingPayCustomerOrder(order)
        if (accountingPayCustomerOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return accountingPayCustomerOrder
        }

        //因为项目是医院设置的，要么减，要么不减，所以不会报错
        val itemCompleteOrder = iItemRuleService.completeOrder(order)
        val orderCompleteOrder = iOrderRuleService.completeOrder(itemCompleteOrder.order)
        iPayCustomerOrderService.setOrderDetailItemInfo(orderCompleteOrder.order)
        return returnSuccess(orderCompleteOrder.order)
    }

    /**
     * 订单下单
     */
    @PostMapping("completeOrder")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("customer:order:place")
    open fun completeOrder(@RequestBody vo: PayCustomerOrderSaveVo): ResponseBody {
        //保存的变成订单实体类
        val order = iPayCustomerOrderService.saveOrderVoToOrder(vo)
        if (order.details.isNullOrEmpty()) {
            return returnError(ErrorCode.OPERATION_DATA_ERROR, "请选择收款项目")
        }
        //处理金额
        val accountingPayCustomerOrder = iPayCustomerOrderService.accountingPayCustomerOrder(order)
        if (accountingPayCustomerOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return accountingPayCustomerOrder
        }
        //项目优惠
        val itemCompleteOrder = iItemRuleService.completeOrder(order)
        if (itemCompleteOrder.responseBodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return itemCompleteOrder.responseBody
        }
        //订单优惠
        val orderCompleteOrder = iOrderRuleService.completeOrder(itemCompleteOrder.order)
        if (orderCompleteOrder.responseBodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return orderCompleteOrder.responseBody
        }

        val setOrder = orderCompleteOrder.order    //计算处理完成后的订单，之后操作都是处理它
        if (setOrder.id == 0L) {
            //添加订单
            val saveNewOrder = saveNewOrder(setOrder)
            if (saveNewOrder.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return saveNewOrder
            }
        } else {
            //修改订单
            val updateOrder = updateOrder(setOrder)
            if (updateOrder.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return updateOrder
            }
        }
        //订单优惠记录保存
        if (setOrder.payCustomerOrderDiscountLog != null) {
            iPayCustomerOrderService
                .addPayCustomerOrderDiscountLog(setOrder.payCustomerOrderDiscountLog!!, setOrder.id)
        }
        //项目优惠保存
        if (setOrder.itemDiscountLogs != null) {
            iPayCustomerOrderService
                .addPayCustomerOrderItemDiscountRuleLogs(setOrder.itemDiscountLogs!!, setOrder.id)
        }
        val completeOrder = iPayCustomerOrderService.completeOrder(setOrder)
        if (completeOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return completeOrder
        }
        iPayCustomerOrderService.setOrderDetailItemInfo(setOrder)
        return returnSuccess(setOrder)
    }

    /**
     * 保存订单（只保存）
     */
    @PostMapping("onlySaveOrder")
    @Transactional
    @PermsCode("customer:order:save")
    open fun onlySaveOrder(@RequestBody vo: PayCustomerOrderSaveVo): ResponseBody {
        val order = iPayCustomerOrderService.saveOrderVoToOrder(vo)

        iPayCustomerOrderService.accountingPayCustomerOrder(order)
        if (order.id != 0L) {
            val updateOrder = updateOrder(order)
            if (updateOrder.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return updateOrder
            }
        } else {
            val saveNewOrder = saveNewOrder(order)
            if (saveNewOrder.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return saveNewOrder
            }
        }
        return returnSuccess(order)
    }

    @PostMapping("updateOrderInfo")
    @Transactional
    @PermsCode("customer:order:update")
    open fun updateOrderInfo(@RequestBody order: CustomerOrderUpdateVo): ResponseBody {
        val updateOrderInfo = iPayCustomerOrderService.updateOrderInfo(order)
        if (updateOrderInfo.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return updateOrderInfo
        }
        return returnSuccess()
    }


    /**
     * 获取客户当日最后一张新增的订单
     */
    @GetMapping("getCustomerLastAddOrder/{id}")
    @Transactional
    open fun getCustomerLastAddOrder(@PathVariable id: Long): ResponseBody {
        val vo = PayCustomerOrderSelectVo()
        vo.status = Status.NEW_ADD
        vo.createDay = Date()
        vo.subCompanyId = getContext().subCompanyId
        val order = iCustomerInfoService.getCustomerLastOrder(id, vo) ?: return returnSuccess()

        order.details = iPayCustomerOrderService.getDetailList(order.id)
        iPayCustomerOrderService.accountingPayCustomerOrder(order)
        //因为项目是医院设置的，要么减，要么不减，所以不会报错
        val itemCompleteOrder = iItemRuleService.completeOrder(order)
        val orderCompleteOrder = iOrderRuleService.completeOrder(itemCompleteOrder.order)
        iPayCustomerOrderService.setOrderDetailItemInfo(orderCompleteOrder.order)
        iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, order)
        return returnSuccess(orderCompleteOrder.order)
    }


    /**
     * 订单付款
     */
    @PostMapping("payOrder")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("customer:order:pay")
    open fun payOrder(@RequestBody vo: PayOrderVo): ResponseBody {
        val printList = mutableListOf<PayOrderPrintShowVo>()


        for (payLog in vo.payMoneys) {
            if (vo.payTime != null) {
                payLog.createTime = vo.payTime!!
            }

            //找到订单
            val orderInfo = iPayCustomerOrderService.getOrderInfo(payLog.orderId) ?: return returnError(
                ErrorCode.OPERATION_DATA_ERROR,
                "未找到订单，请刷新重试"
            )
            //添加支付记录
            val addPayOrderLog = iCustomerInfoService.addPayOrderLog(payLog)
            if (addPayOrderLog.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return addPayOrderLog
            }
            //充值
            var paySumMoney = 0L   //付订单的金额
            val payTypeBuffer = StringBuffer() //支付方式（打印用）
            if (payLog.details != null) {
                for (detail in payLog.details!!) {
                    paySumMoney += detail.payMoney
                    payTypeBuffer.append(detail.payType.typeName + " " + detail.moneyShow + " ")
                    if (detail.payType == TypeEnum.CUSTOMER_PAY_TYPE_ACCOUNT || detail.payType == TypeEnum.CUSTOMER_PAY_TYPE_ACCOUNT_GIFT) {
                        //余额付款，不用充值
                        continue
                    }
                    val topUpBalance = iCustomerInfoService.topUpBalance(
                        orderInfo.customerId,
                        detail.payMoney,
                        detail.payType,
                        TypeEnum.PAY_TYPE_BALANCE_ORDER_PAY,
                        vo.remark,
                        0,
                        detail.id,
                        vo.payTime
                    )
                    if (topUpBalance.bodyIsError()) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                        return topUpBalance
                    }
                }
            }
            payLog.originalPrice = orderInfo.originalPrice
            payLog.remark = vo.remark
            payLog.theCumulativeBalance =
                iCustomerInfoService.getCustomerAccount(orderInfo.customerId, getContext().subCompanyId).amountOwed
            payLog.createTime = vo.payTime ?: Date()

            //付款
            val payOrder = iPayCustomerOrderService.payOrder(payLog.orderId, paySumMoney, payLog)
            if (payOrder.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return payOrder
            }
            val updateOrderPayLogAll = iPayCustomerOrderService.updateOrderPayLogAll(payLog)
            if (updateOrderPayLogAll.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return updateOrderPayLogAll
            }
            val customerInfo = iCustomerInfoService.getById(orderInfo.customerId)
            if (customerInfo == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return returnError(
                    ErrorCode.OPERATION_DATA_ERROR,
                    "患者信息错误"
                )
            }
            val printShowVo = iPayCustomerOrderService.payLogToPrint(payLog)
            if (printShowVo.isNotEmpty()) {
                printList.addAll(printShowVo)
            }
        }
        return returnSuccess(printList)
    }

    /**
     * 订单付款记录
     */
    @GetMapping("getOrderPayLogList/{id}")
    @Transactional
    open fun getOrderPayLogList(@PathVariable id: Long): ResponseBody {
        val orderPayLogList = iPayCustomerOrderService.getOrderPayLogList(id)
        for (payLog in orderPayLogList) {
            val dept = iCompanyDeptService.getDept(payLog.subCompanyId)
            payLog.subCompanyName = dept?.name ?: ""
            val user = iCompanyUserService.getUser(payLog.createUserId)
            payLog.createUserName = user?.realName ?: ""
            val order = iPayCustomerOrderService.getOrderInfo(payLog.orderId)
            payLog.doctorName = if (order?.masterUserId != null) {
                val doctor = iCompanyUserService.getUser(order.masterUserId!!)
                doctor?.realName ?: ""
            } else {
                ""
            }
            payLog.payStatus = Status.NORMAL
        }
        return returnSuccess(orderPayLogList)
    }

    /**
     * 订单付款记录
     */
    @PostMapping("updateOrderPayLogInfo")
    @Transactional
    open fun updateOrderPayLogInfo(@RequestBody vo: CustomerPayLogUpdateVo): ResponseBody {
        val updateOrderPayLogInfo = iPayCustomerOrderService.updateOrderPayLogInfo(vo)
        if (updateOrderPayLogInfo.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return updateOrderPayLogInfo
        }
        return returnSuccess()
    }


    /**
     * 付款打印
     */
    @GetMapping("getPrintListByPayLogId/{id}")
    @Transactional
    open fun getPrintListByPayLogId(@PathVariable id: Long): ResponseBody {
        val printList = mutableListOf<PayOrderPrintShowVo>()
        val printShowVo = iPayCustomerOrderService.payLogToPrint(id)
        if (printShowVo.isNotEmpty()) {
            printList.addAll(printShowVo)
        }
        return returnSuccess(printList)
    }

    /**
     * 订单付款打印
     */
    @GetMapping("getPrintListByOrderId/{id}")
    @Transactional
    open fun getPrintListByOrderId(@PathVariable id: Long): ResponseBody {
        val printList = mutableListOf<PayOrderPrintShowVo>()
        val printShowVo = iPayCustomerOrderService.orderAllPayLogToPrint(id)
        if (printShowVo.isNotEmpty()) {
            printList.addAll(printShowVo)
        }
        return returnSuccess(printList)
    }


    /**
     * 付欠费
     */
    @PostMapping("payDebtOrder")
    @Transactional
    @PermsCode("customer:order:pay")
    open fun payDebtOrder(@RequestBody vo: PayOrderVo): ResponseBody {
        //直接调用付款的方法，已经统一了
        return payOrder(vo)
    }

    /**
     * 退款
     */
    @PostMapping("refundOrder")
    @Transactional
    @PermsCode("customer:order:refund")
    open fun refundOrder(@RequestBody vo: RefundByOrderVo): ResponseBody {

        val refundOrder = iPayCustomerOrderService.refundOrder(vo)
        if (refundOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return refundOrder
        }

        return returnSuccess()
    }

    /**
     * 待收费列表(默认今日)
     */
    @PostMapping("/toChargeList")
    @PermsCode("pay:order:charge:list")
    @Transactional
    open fun toChargeList(@RequestBody vo: PayCustomOrderToChargeVo): ResponseBody {
        if (vo.day == null) {
            vo.day = Date()
        }
        vo.companyId = getContext().companyId
        vo.subCompanyId = getContext().subCompanyId
        val orderPage = iWebCompanyDeptService.toChargeList(vo)
        val resList = arrayListOf<PayCustomerOrder>()
        for (order in orderPage.records) {
            order.details = iPayCustomerOrderService.getDetailList(order.id)
            iPayCustomerOrderService.getOrderLeftJoinSet(order)
            if (order.status == Status.NEW_ADD) {
                iPayCustomerOrderService.accountingPayCustomerOrder(order)
                //因为项目是医院设置的，要么减，要么不减，所以不会报错
                val itemCompleteOrder = iItemRuleService.completeOrder(order)
                val orderCompleteOrder = iOrderRuleService.completeOrder(itemCompleteOrder.order)
                iPayCustomerOrderService.setOrderDetailItemInfo(orderCompleteOrder.order)
                iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, orderCompleteOrder.order)
                resList.add(orderCompleteOrder.order)
            } else {
                iPayCustomerOrderService.setOrderDetailItemInfo(order)
                order.customerInfo = iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, order)
                resList.add(order)
            }
        }
        orderPage.records = resList
        return returnSuccess(orderPage)
    }

    /**
     * 待收费数量
     */
    @GetMapping("/toChargeCount")
    @PermsCode("pay:order:charge:list")
    @Transactional
    open fun toChargeCount(): ResponseBody {
        return returnSuccess(
            iWebCompanyDeptService.toChargeCount(
                PayCustomOrderToChargeVo(
                    companyId = getContext().companyId,
                    subCompanyId = getContext().subCompanyId,
                    day = Date()
                )
            )
        )
    }

    /**
     * 已收费列表
     */
    @PostMapping("/hasChargeList")
    @PermsCode("pay:order:has:charge:list")
    @Transactional
    open fun hasChargeList(@RequestBody vo: PayCustomOrderToChargeVo): ResponseBody {
        if (vo.day == null) {
            vo.day = Date()
        }
        val hasChargeList = iWebCompanyDeptService.hasChargeList(vo)
        for (order in hasChargeList.records) {
            iCustomerInfoService.getJoinInfoByCustomerId(order.customerId, order)
            iPayCustomerOrderService.getOrderLeftJoinSet(order)
        }
        return returnSuccess(hasChargeList)
    }

    /**
     * 已收费数量(侧边栏显示用)
     */
    @GetMapping("/hasChargeCount")
    @PermsCode("pay:order:has:charge:list")
    @Transactional
    open fun hasChargeCount(): ResponseBody {
        return returnSuccess(
            iWebCompanyDeptService.hasChargeCount(
                PayCustomOrderToChargeVo(
                    companyId = getContext().companyId,
                    subCompanyId = getContext().subCompanyId,
                    day = Date()
                )
            )
        )
    }


    /**
     * 显示今日新增患者，新增预约，实收金额，随访人员，今日就诊
     */
    @PostMapping("todayStatistics")
    @Transactional
    open fun todayStatistics(): ResponseBody {
        return returnSuccess(iWebCompanyDeptService.todayStatistics(getContext().subCompanyId))
    }

    /**
     * 设置订单项目完成时间
     */
    @PostMapping("setDetailStartTime")
    @Transactional(rollbackFor = [Exception::class])
    open fun setDetailStartTime(@RequestBody vo: PayCustomerOrderDetailStartTimeSetVo): ResponseBody {
        val saveDetailUseStartTime = iPayCustomerOrderService.saveDetailUseStartTime(vo.detailId, vo.startTime)
        if (saveDetailUseStartTime.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return saveDetailUseStartTime
        }
        return returnSuccess()
    }

    /**
     * 获取订单信息以及详情（下单了的）
     */
    @GetMapping("getOrderInfoAndDetail/{id}")
    @Transactional
    open fun getOrderInfoAndDetail(@PathVariable id: Long): ResponseBody {
        val orderInfo = iPayCustomerOrderService.getOrderInfo(id) ?: return returnSuccess()
        return if (orderInfo.status == Status.NEW_ADD) {
            orderInfo.details = iPayCustomerOrderService.getDetailList(orderInfo.id)
            iPayCustomerOrderService.accountingPayCustomerOrder(orderInfo)
            //因为项目是医院设置的，要么减，要么不减，所以不会报错
            val itemCompleteOrder = iItemRuleService.completeOrder(orderInfo)
            val orderCompleteOrder = iOrderRuleService.completeOrder(itemCompleteOrder.order)
            returnSuccess(orderCompleteOrder.order)
        } else {
            val customer = iCustomerInfoService.getById(orderInfo.customerId)
            if (customer != null) {
                orderInfo.customerInfo = customer
            }
            if (orderInfo.masterUserId != null) {
                val doctor = iCompanyUserService.getUser(orderInfo.masterUserId!!)
                if (doctor != null) {
                    orderInfo.masterUserName = doctor.realName
                }
            }
            orderInfo.details = iPayCustomerOrderService.getDetailList(id)
            iPayCustomerOrderService.setOrderRefund(orderInfo)
            iPayCustomerOrderService.setOrderGiftOfGoldPay(orderInfo)
            returnSuccess(orderInfo)
        }

    }

    /**
     * 设置订单项目完成
     */
    @PostMapping("setDetailEnd/{id}")
    @Transactional(rollbackFor = [Exception::class])
    open fun setDetailEnd(@PathVariable id: Long): ResponseBody {
        val res = iPayCustomerOrderService.setDetailToEnd(id)
        if (res.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
        }
        return res
    }

    /**
     * 设置订单全部完成
     */
    @PostMapping("setOrderAllEnd/{id}")
    @Transactional(rollbackFor = [Exception::class])
    open fun setOrderAllEnd(@PathVariable id: Long): ResponseBody {
        val details = iPayCustomerOrderService.getDetailList(id)
        for (detail in details) {
            val res = iPayCustomerOrderService.setDetailToEnd(detail.id)
            if (res.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            }
        }
        val orderHaveDetailToEnd = iPayCustomerOrderService.orderHaveDetailToEnd(id)
        if (orderHaveDetailToEnd.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
        }
        return orderHaveDetailToEnd
    }

    /**
     * 删除订单（只有新增的才能删除）
     */
    @PostMapping("delOrder/{id}")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("customer:order:new:del")
    open fun delOrder(@PathVariable id: Long): ResponseBody {
        val delOrder = iPayCustomerOrderService.delOrder(id)
        if (delOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return delOrder
        }
        return returnSuccess()
    }

    /**
     * 删除已付款的订单
     */
    @PostMapping("delOrderHasPay/{id}")
    @Transactional(rollbackFor = [Exception::class])
    @PermsCode("customer:order:del")
    open fun delOrderHasPay(@PathVariable id: Long): ResponseBody {
        val delOrderHasPay = iPayCustomerOrderService.delOrderHasPay(id)
        if (delOrderHasPay.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return delOrderHasPay
        }
        return returnSuccess()
    }


    /**
     * 新增订单
     */
    open fun saveNewOrder(order: PayCustomerOrder): ResponseBody {
        //添加订单
        val createOrder = iCustomerInfoService.createOrder(order)
        if (createOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return createOrder
        }

        //订单添加明细
        for (detail in order.details!!) {
            detail.orderId = order.id
            detail.itemSumMoney = detail.realMoney
            detail.itemPrice = detail.realPrice
            val addDetail = iPayCustomerOrderService.addDetail(detail)
            if (addDetail.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return addDetail
            }
        }
        return returnSuccess()
    }


    /**
     * 修改订单
     */
    open fun updateOrder(order: PayCustomerOrder): ResponseBody {
        //修改
        val updateOrder = iPayCustomerOrderService.updateOrder(
            order.id,
            order.masterUserId,
            order.secondaryUserId,
            order.remark,
            order.orderManualSumMoney
        )
        if (updateOrder.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return updateOrder
        }
        val delDetail = iPayCustomerOrderService.delAllDetail(order.id)
        if (delDetail.bodyIsError()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
            return delDetail
        }
        //订单添加明细
        for (detail in order.details!!) {
            detail.orderId = order.id
            detail.itemPrice = detail.realPrice
            detail.itemSumMoney = detail.realMoney
            val addDetail = iPayCustomerOrderService.addDetail(detail)
            if (addDetail.bodyIsError()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
                return addDetail
            }
        }
        return returnSuccess()
    }


}

